import React from 'react';
import {Table} from 'antd';
import PropTypes from 'prop-types';
import routes from './routes';
import {TABLE, PAGINATION_OPTIONS, FIXED_COLUMN_WIDTH, COMMON_TABLE_QUERY_FAIL_TEXT, COMMON_TABLE_EMPTY_TEXT, PAGE, DATETIME_FORMAT} from '../constants';
import {Link} from 'react-router-dom';
import {hasPermissions} from './utils';
import {transportType, partOrderStatus, currency} from '../Enum';
import {conventEnumValueToString, formatAmount, formatPercent} from '../utils';
import {PERMISSIONS} from './constants';
import DropdownMenu from 'Shared/components/DropdownMenu';
import WrappedPopconfirm from '../common/WrappedPopconfirm';
import {injectIntl} from './intl';
import moment from 'moment';
export class TablePanel extends React.PureComponent {
    state = {
        loading: false
    };

    closeConfirm = id => {
        this.setState({
            loading: true
        });
        this.props.onClickClose(id).then(() => {
            this.setState({
                loading: false
            });
        });
    };

    onChangeSort = (pagination, filters, sorter) => {
        this.props.onChangeSort({
            pageIndex: pagination.current - 1,
            pageSize: pagination.pageSize,
            sortedColumnKey: sorter.columnKey,
            sortedOrder: sorter.order,
        });
    };

    render() {
        const {formatMessage} = this.props.intl;
        const {pageIndex, pageSize, total, permissions} = this.props;
        const pagination = {
            total,
            pageSize,
            current: pageIndex + 1,
            ...PAGINATION_OPTIONS
        };
        const locale = {
            emptyText: this.props.errorMessage ? COMMON_TABLE_QUERY_FAIL_TEXT : COMMON_TABLE_EMPTY_TEXT
        };
        const columns = [
            {
                title: formatMessage({
                    id: 'tablePanel.text.dealerCode',
                    defaultMessage: '总代编号'
                }),
                dataIndex: 'dealerCode'
            },
            {
                title: formatMessage({
                    id: 'tablePanel.text.code',
                    defaultMessage: '备件订单号'
                }),
                dataIndex: 'code',
                sorter: true
            },
            {
                title: formatMessage({
                    id: 'tablePanel.text.partOrderTypeName',
                    defaultMessage: '订单类型'
                }),
                dataIndex: 'partOrderTypeName',
            },
            {
                title: formatMessage({
                    id: 'tablePanel.text.transportType',
                    defaultMessage: '发运方式'
                }),
                dataIndex: 'transportType',
                render: text => conventEnumValueToString(transportType, text)
            },
            {
                title: formatMessage({
                    id: 'tablePanel.text.submitTime',
                    defaultMessage: '提报日期'
                }),
                dataIndex: 'submitTime',
                sorter: true,
                render: text => moment(text).format('YYYY-MM-DD HH:mm:ss')
            },
            {
                title: formatMessage({
                    id: 'tablePanel.text.status',
                    defaultMessage: '订单状态'
                }),
                dataIndex: 'status',
                render: text => conventEnumValueToString(partOrderStatus, text)
            },
            {
                title: formatMessage({
                    id: 'tablePanel.text.currency',
                    defaultMessage: '币种'
                }),
                dataIndex: 'currency',
                render: text => conventEnumValueToString(currency, text)
            },
            {
                title: formatMessage({
                    id: 'tablePanel.text.totalAmount',
                    defaultMessage: '订单金额'
                }),
                dataIndex: 'totalAmount',
                render: text => formatAmount(text)
            },
            {
                title: formatMessage({
                    id: 'tablePanel.text.varietyMeetRate',
                    defaultMessage: '累计品种满足率'
                }),
                dataIndex: 'varietyMeetRate',
                render: text => formatPercent(text)
            },
            {
                title: formatMessage({
                    id: 'tablePanel.text.amountMeetFullRate',
                    defaultMessage: '累计金额满足率'
                }),
                dataIndex: 'amountMeetFullRate',
                render: text => formatPercent(text)
            },
            {
                title: formatMessage({
                    id: 'tablePanel.text.totalAmountFullRate',
                    defaultMessage: '累计出运金额'
                }),
                dataIndex: 'totalAmountFullRate',
                render: text => formatAmount(text)
            },
            {
                title: formatMessage({
                    id: 'tablePanel.text.deliverInvoiceCode',
                    defaultMessage: '交付发票号'
                }),
                dataIndex: 'deliverInvoiceCode',
                sorter: true
            },
            {
                title: formatMessage({
                    id: 'tablePanel.text.delivedDate',
                    defaultMessage: '交付日期'
                }),
                dataIndex: 'delivedDate',
                sorter: true,
                render: (text, record) => record.delivedDate ? moment(text).format('YYYY-MM-DD HH:mm:ss') : null
            },
            {
                title: formatMessage({
                    id: 'tablePanel.text.closedDate',
                    defaultMessage: '关闭日期'
                }),
                dataIndex: 'closedDate',
                sorter: true,
                render: text => text ? moment(text).format('YYYY-MM-DD HH:mm:ss') : null
            }];
            
        columns.push({
            title: formatMessage({
                id: 'tablePanel.column.operate',
                defaultMessage: '操作'
            }),
            dataIndex: 'id',
            key: 'id',
            width: FIXED_COLUMN_WIDTH,
            fixed: 'right',
            render: (text, record) => {
                const menus = [
                    {
                        id: PERMISSIONS.deliver,
                        children: <Link key="deliver" to={routes.deliver.format(record.id)}>{
                            formatMessage({
                                id: 'tablePanel.operation.deliver',
                                defaultMessage: '交付'
                            })
                        }</Link>,
                        hidden: !(hasPermissions(permissions, PERMISSIONS.deliver) && hasPermissions(record.options, PERMISSIONS.deliver)),
                    }, {
                        id: PERMISSIONS.close,
                        children: (ref =>
                            <WrappedPopconfirm
                                key="close"
                                placement="topLeft"
                                onConfirm={this.closeConfirm}
                                id={record.id}
                                title={formatMessage({
                                    id: 'tablePanel.message.close',
                                    defaultMessage: '是否继续？'
                                })}>
                                <a>{formatMessage({
                                    id: 'tablePanel.operation.close',
                                    defaultMessage: '关闭'
                                })}</a>
                            </WrappedPopconfirm>
                        ),
                        hidden: !(hasPermissions(permissions, PERMISSIONS.close) && hasPermissions(record.options, PERMISSIONS.close)),
                    }, {
                        id: PERMISSIONS.detail,
                        children: <Link key="detail" to={routes.detail.format(record.id)}>{
                            formatMessage({
                                id: 'tablePanel.operation.detail',
                                defaultMessage: '详情'
                            })
                        }</Link>,
                        hidden: !(hasPermissions(permissions, PERMISSIONS.detail) && hasPermissions(record.options, PERMISSIONS.detail)),
                    }];
                return <DropdownMenu key={record.id} menus={menus} primaryLength={1} id={record.id} />;
            }
        });
        return (
            <div>
                <Table
                    className="white-space-nowrap"
                    columns={columns}
                    dataSource={this.props.data}
                    rowKey="id"
                    pagination={pagination}
                    loading={this.props.loading || this.state.loading}
                    onChange={this.onChangeSort}
                    locale={locale}
                    {...TABLE}>
                </Table>
            </div>
        );
    }
}

TablePanel.propTypes = {
    data: PropTypes.array.isRequired,
    errorMessage: PropTypes.string.isRequired,
    loading: PropTypes.bool.isRequired,
    permissions: PropTypes.array.isRequired,
    total: PropTypes.number.isRequired,
    onChangeSort: PropTypes.func.isRequired,
    intl: PropTypes.object,
    pageIndex: PropTypes.number,
    pageSize: PropTypes.number,
    refreshListData: PropTypes.func,
    sortedColumnKey: PropTypes.string,
    sortedOrder: PropTypes.string,
};

import {connect} from 'react-redux';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
import {
    tableSearch,
    onClickClose
} from './actions';

const getData = selectorFactory(['page', 'domainData', 'list', 'data']);
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const getIsDealerUser = selectorFactory(['page', 'domainData', 'initData', 'isDealerUser']);

const mapStateToProps = state => ({
    data: getData(state),
    loading: state.getIn(['page', 'domainData', 'list', 'isFetching']),
    total: state.getIn(['page', 'domainData', 'list', 'total']),
    errorMessage: state.getIn(['page', 'domainData', 'list', 'message']),
    pageIndex: state.getIn(['page', 'appState', 'queryBySort', 'pageIndex']),
    pageSize: state.getIn(['page', 'appState', 'queryBySort', 'pageSize']),
    sortedColumnKey: state.getIn(['page', 'appState', 'queryBySort', 'sortedColumnKey']),
    sortedOrder: state.getIn(['page', 'appState', 'queryBySort', 'sortedOrder']),
    isDealerUser: getIsDealerUser(state),
    permissions: getPermissions(state),
});

const mapDispatchToProps = dispatch => ({
    onChangeSort: option => dispatch(tableSearch(option)),
    refreshListData: () => dispatch(tableSearch()),
    onClickClose: id =>
        dispatch(onClickClose(id)).then(success => {
            if(success) dispatch(tableSearch({
                pageIndex: PAGE.index
            }));
            return success;
        }),
});

export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(TablePanel));

